package cn.ywang.spring.customized.framework.webmvc;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 视图解析器
 * 1. 将静态页面转换为动态页面
 * 2. 根据用户传参的不同，产生不同的结果，最终生成字符串，通过response返回给用户
 *
 * @author BeatificWang
 * @date 2018/11/7 21:45
 */

public class ViewResolver {
	private static final Pattern pattern = Pattern.compile("$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
	private String viewName;
	private File templateFile;

	public ViewResolver(String viewName, File templateFile) {
		this.viewName = viewName;
		this.templateFile = templateFile;
	}

	public String resolveViewName(ModelAndView mv) throws Exception {
		StringBuffer sb = new StringBuffer();
		RandomAccessFile randomAccessFile = new RandomAccessFile(this.templateFile, "r");
		try {
			String line = null;
			while ((line = randomAccessFile.readLine()) != null) {
				line = new String(line.getBytes("ISO-8859-1"), "utf-8");
				Matcher matcher = this.matcher(line);
				while (matcher.find()) {
					for (int i = 1; i < matcher.groupCount(); i++) {
						//要把${}中间的这个字符串给取出来
						String paramName = matcher.group(i);
						Object paramValue = mv.getModel().get(paramName);
						if (null == paramValue) {
							continue;
						}
						line = line.replaceAll("$\\{" + paramName + "\\}", paramValue.toString());
						line = new String(line.getBytes("utf-8"), "ISO-8859-1");
					}
				}
				sb.append(line);
			}
		} finally {
			randomAccessFile.close();
		}
		return sb.toString();
	}

	private Matcher matcher(String line) {
		Matcher matcher = pattern.matcher(line);
		return matcher;
	}

	public String getViewName() {
		return this.viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}

	public File getTemplateFile() {
		return this.templateFile;
	}

	public void setTemplateFile(File templateFile) {
		this.templateFile = templateFile;
	}
}
